% save the data as xlsx format
% RuiGuo
clear all;

dat_dir = 'H:\Projects\MyoDynT1\EXPData\Phantom\Analysis\vsMOLLI53';
%generate a refference map
ROI_name = 'Template.mat';
file_path = [ dat_dir  filesep ROI_name ];
T1_T2 = 2 ;
[ Ref_mask_map,Ref_map] = generaterefferencemap( file_path,T1_T2 );
% ROI_path = [dat_dir filesep 'ROIs\ROIs.mat' ];
% [ Ref_mask_map,Ref_map] = generaterefferencemapFromROI( file_path,ROI_path,T1_T2);

ROI_temp = edge(sum(Ref_mask_map,3));
ROI_temp = ROI_temp.*((T1_T2==1)*3000+(T1_T2==2)*200);
ROI_temp = Ref_map+ROI_temp;
f = figure('Name','ROI of refference', 'visible','on');
imagesc(ROI_temp,(T1_T2==1)*[ 0 3000]+(T1_T2==2)*[0 300]),colormap(jet);
axis normal;
axis off;
print(f,'-dpng', [ dat_dir filesep  'ROIforstatistics.png']);


data_type_parten = '.mat';
dir_info = dir(dat_dir);
file_length = length(dir_info);
result_cell = cell(1,file_length);
file_flag = zeros(1,file_length);
file_name_cell = cell( 1,file_length );


%get reference value
T1_T2 =1;
file_name = 'Ref.mat';
file_path = [ dat_dir  filesep file_name ];
[Ref_avg, Ref_std] = readavgsdofphantom( file_path,Ref_mask_map,T1_T2,1) ;

for file_ix = 1:file_length
    file_name = dir_info(file_ix,1).name ;
    type_pos = regexpi(file_name,data_type_parten);
    if(strcmp(file_name ,ROI_name)==0)
        if( ~isempty( type_pos))
            file_flag(1,file_ix ) = 1 ;
            %get the data;
            file_path = [ dat_dir  filesep file_name ];
            [ravg, rstd] = readavgsdofphantom( file_path,Ref_mask_map,T1_T2,1) ;
            result_cell{1,file_ix}.avg =  ravg;
            result_cell{1,file_ix}.std =  rstd;
            file_name_cell{ 1, file_ix } = file_name ;
        end
    end
end
%output to xls file
T1_T2_str=[ 'T1';'T2'];
tmStr = datestr(now,'YYYY_mm_DD');
xlsxfilenm = [T1_T2_str(T1_T2,:) '_result_' tmStr '.xlsx'];
filepath = [ dat_dir filesep xlsxfilenm];
% fp=fopen(filepath,'a');  % creat new file;
% fclose(fp);

try
    Excel=actxgetrunningserver('Excel.application');
catch
    Excel=actxserver('Excel.application');
end

Excel.visible=1;
Workbooks= Excel.Workbooks;
if exist(filepath,'file' )
    Workbook = Excel.Workbooks.Open(filepath);
else
    Workbook = Excel.Workbooks.Add;
    Workbook.SaveAs(filepath);
end
Sheets=Excel.Activeworkbook.Sheets;
Sheet1=Sheets.Item(1);
Sheet1.Activate;

%output name
start_row = 3 ;
row_ix =  1 ;
Start_col ='A';
Sub_item = 'B';
Dat_st_col = 'C';
Merage_row = 1;
%export raw fitting result.
for file_ix = 1: file_length
    if( file_flag(1,file_ix ) ==1  )
        scanning_name  = file_name_cell{ 1, file_ix };
        Merage_info = [ Start_col num2str(row_ix) ':' Start_col num2str(row_ix + Merage_row )];
        Sheet1.Range(Merage_info).MergeCells=1;
        %set  name value
        ActivesheetRange = get(Sheet1,'Range',Merage_info);
        set(ActivesheetRange, 'Value', scanning_name);
        % set average info  and output averge to the tables
        average_tag_range = [ Sub_item num2str(row_ix)];
        ActivesheetRange = get(Sheet1,'Range',average_tag_range);
        set(ActivesheetRange, 'Value', 'AVG');
        avg = result_cell{1,file_ix}.avg ;
        len_avg = length( avg );
        if(len_avg > 24 )
            average_range = [ Dat_st_col num2str(row_ix) ':' Start_col char( mod(len_avg,24 )+65 ) num2str(row_ix)];
        else
            average_range = [ Dat_st_col num2str(row_ix) ':' char( mod(len_avg,24 )+Dat_st_col-1 ) num2str(row_ix) ];
        end
        
        ActivesheetRange = get(Sheet1,'Range',average_range);
        set(ActivesheetRange, 'Value', avg);
        % set std info  and output the std to the tables
        std_tag_range = [ Sub_item num2str(row_ix + Merage_row )];
        ActivesheetRange = get(Sheet1,'Range',std_tag_range);
        set(ActivesheetRange, 'Value', 'SD');
        std = result_cell{1,file_ix}.std ;
        
        len_std = length( std );
        if(len_std > 24 )
            std_range = [ Dat_st_col num2str(row_ix+ Merage_row) ':' Start_col char( mod(len_std,24 )+65 ) num2str(row_ix+ Merage_row)];
        else
            std_range = [ Dat_st_col num2str(row_ix+ Merage_row) ':' char( mod(len_std,24 )+Dat_st_col-1 )  num2str(row_ix+ Merage_row)];
        end
        
        ActivesheetRange = get(Sheet1,'Range',std_range);
        set(ActivesheetRange, 'Value', std );
        row_ix = row_ix + Merage_row*2;
    end
end

%outpur percentage error
row_ix = row_ix + 3;
Start_col ='A';
Sub_item = 'B';
Dat_st_col = 'C';
%export raw fitting result.
for file_ix = 1: file_length
    if( file_flag(1,file_ix ) ==1  )
        scanning_name  = file_name_cell{ 1, file_ix };
        %set  name value
        name_range =  [ Start_col num2str(row_ix)];
        ActivesheetRange = get(Sheet1,'Range',name_range);
        set(ActivesheetRange, 'Value', scanning_name);
        % set average info  and output averge to the tables
        average_tag_range = [ Sub_item num2str(row_ix)];
        ActivesheetRange = get(Sheet1,'Range',average_tag_range);
        set(ActivesheetRange, 'Value', 'Percentage Rrror[%]');
        avg = result_cell{1,file_ix}.avg ;
        len_avg = length( avg );
        if(len_avg > 24 )
            average_range = [ Dat_st_col num2str(row_ix) ':' Start_col char( mod(len_avg,24 )+65 ) num2str(row_ix)];
        else
            average_range = [ Dat_st_col num2str(row_ix) ':' char( mod(len_avg,24 )+Dat_st_col-1 ) num2str(row_ix) ];
        end
        
        
        Lambda = 0.7003;
        TR = 2.8803;% %ms
        FA=Lambda*4/180*pi;
        alpha =1; % 1./(1+avg./TR*log(cos(FA)));
        
        ActivesheetRange = get(Sheet1,'Range',average_range);
        Percentage_error = round(( alpha.*(avg -Ref_avg)./Ref_avg*100)*10)/10;
        set(ActivesheetRange, 'Value', Percentage_error);
        % set std info  and output the std to the tables
        row_ix = row_ix + 1;
    end
end




%output CV
row_ix = row_ix + 3;
Start_col ='A';
Sub_item = 'B';
Dat_st_col = 'C';
for file_ix = 1: file_length
    if( file_flag(1,file_ix ) ==1  )
        scanning_name  = file_name_cell{ 1, file_ix };
        %set  name value
        name_range =  [ Start_col num2str(row_ix)];
        ActivesheetRange = get(Sheet1,'Range',name_range);
        set(ActivesheetRange, 'Value', scanning_name);
        
        % set std info  and output the std to the tables
        std_tag_range = [ Sub_item num2str(row_ix  )];
        ActivesheetRange = get(Sheet1,'Range',std_tag_range);
        set(ActivesheetRange, 'Value', 'CV');
        std = result_cell{1,file_ix}.std ;
        avg = result_cell{1,file_ix}.avg ;
        cv = (std./avg)*100;
        len_std = length( std );
        if(len_std > 24 )
            std_range = [ Dat_st_col num2str(row_ix) ':' Start_col char( mod(len_std,24 )+65 ) num2str(row_ix)];
        else
            std_range = [ Dat_st_col num2str(row_ix) ':' char( mod(len_std,24 )+Dat_st_col-1 )  num2str(row_ix)];
        end
        
        ActivesheetRange = get(Sheet1,'Range',std_range);
        set(ActivesheetRange, 'Value', cv );
        row_ix = row_ix +1;
    end
end

Workbook.SaveAs(filepath);
invoke(Workbook, 'Close');
invoke(Excel, 'Quit');
delete(Excel);